package com.yr.visa.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.google.common.base.Predicate;

public class JsonUtil {

	public static String getDefaultJsonString(JSONObject jo){
		String defaultValue="{}";
		if(jo == null){
			return defaultValue;
		}
		
		return jo.toJSONString();
	}
	
	public static JSONObject filter(JSONArray array,Predicate<JSONObject> pre){
		if(array == null || array.isEmpty()){
			return null;
		}
		for(int i=0;i<array.size();i++){
			JSONObject jo = array.getJSONObject(i);
			if(pre.apply(jo)){
				return jo;
			}
		}
		return null;
	}
	
	public static String toJsonPathString(JSONObject obj,String path){
		return toJsonPathString(obj, path, "{}");
		
	}
	public static String toJsonPathString(JSONObject obj,String path,String defultValue){
		if(obj == null || path==null){
			return defultValue;
		}
		JSON res =(JSON)JSONPath.eval(obj,path);
		if(res != null){
			return res.toJSONString();
		}
		return defultValue;
		
	}
	
	public static String toPathString(JSONObject obj,String path,String defultValue){
		if(obj == null || path==null){
			return defultValue;
		}
		String res =(String)JSONPath.eval(obj,path);
		if(res != null){
			return res;
		}
		return defultValue;
	}
	
	
	public static <T> T transferPojo(JSONObject jo,Class<T> clazz){
		if(jo == null || clazz == null){
			return null;
		}
		try {
			return jo.toJavaObject(clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	} 
}
